package atguigu2.assist;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @AUTHOR LYF
 * @DATE 2022/2/4
 * @VERSION 1.0
 * @DESC
 * 计数信号量，acquire,release
 *
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);//三个许可，无特定标位？
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到车位");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(3));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println(Thread.currentThread().getName()+"离开");//应该放在释放之前
                    semaphore.release();
                }
            },"Thread-"+i).start();
        }
    }
}
